package redis

import (
	"errors"
	"github.com/go-redis/redis"
	"time"
)

const oneWeek = 7*24*60*60
const oneOfScore = 86400/100

func AddArticle(articleId string) error {
	pipe := rdb.TxPipeline()
	pipe.ZAdd(getKey(KeyArticleTimeZSet), redis.Z{
		Score: float64(time.Now().Unix()),
		Member: articleId,
	})
	pipe.ZAdd(getKey(KeyArticleScoreZSet), redis.Z{
		Score: float64(time.Now().Unix()),
		Member: articleId,
	})
	_,err := pipe.Exec()
	return err
}

// UserVote 用户投票
func UserVote(userId, articleId string, score int8) error {
	//判断文章是否可以投票 文章创建一个星期后不支持该操作
	cTime := rdb.ZScore(getKey(KeyArticleTimeZSet), articleId)
	if float64(time.Now().Unix()) - cTime.Val() > oneWeek {
		return errors.New("文章已超过可投票时间")
	}
	voteLogKey := getKey(KeyArticleVoteZSet)+articleId
	oldScore := rdb.ZScore(voteLogKey, userId).Val()
	if oldScore!=0 && score!=0 {
		return errors.New("不支持的操作")
	}
	realScore := (float64(score)-oldScore)*oneOfScore
	pipe := rdb.TxPipeline()
	//更新文章分数
	pipe.ZIncrBy(getKey(KeyArticleScoreZSet), realScore, articleId)
	//写入投票记录
	if score == 0{
		 //删除记录
		pipe.ZRem(voteLogKey,userId)
	} else{
		pipe.ZAdd(voteLogKey,redis.Z{
			Score: float64(score),
			Member: userId,
		})
	}

	_,err := pipe.Exec()
	return err
}
